//
//  CategoryAdditions.m
//  Doc Ebook
//
//  Created by Hai Nguyen on 9/6/12.
//  Copyright (c) 2012 Hai Nguyen. All rights reserved.
//

#import "AppDelegate.h"
#import "CategoryAdditions.h"
#import "CoreDataHelper.h"

@implementation Category (Additions)

+ (BOOL)insertCategory:(int)catId name:(NSString*)name thumbnail:(UIImage*)thumbnail note:(NSString*)note{
	NSError *err = nil;
	NSManagedObjectContext *managedObjectContext = [mainAppDelegate managedObjectContext];
	if (managedObjectContext == nil){
		return NO;
	}
	Category *category = [NSEntityDescription insertNewObjectForEntityForName:@"Category" inManagedObjectContext:managedObjectContext];
	category.id = [NSNumber numberWithInt:catId];
	category.name = name;
	category.thumbnail = [NSData dataWithData:UIImagePNGRepresentation(thumbnail)];
	category.note = note;
	
	if (![managedObjectContext save:&err]) {
		DEBUG_LOG(@"Error : %@", [err description]);
		return NO;
	}
	return YES;
}

+ (NSArray*)getCategories{
	NSManagedObjectContext *managedObjectContext = [mainAppDelegate managedObjectContext];
	if (managedObjectContext == nil){
		return nil;
	}
	NSArray *lists = nil;
	@try {
		lists = (NSMutableArray*) [CoreDataHelper searchObjectsInContext:@"Category" :nil :nil :NO :managedObjectContext];
	}@catch (NSException * e) {
		DEBUG_LOG(@"%@",[e description]);
    }
	
	return lists;
}

+ (Category*)categoryById:(int)catId{
	NSManagedObjectContext *managedObjectContext = [mainAppDelegate managedObjectContext];
	if (managedObjectContext == nil){
		return nil;
	}
    if (catId < 1) {
        return nil;
    }
    NSArray *resultArray = nil;
    NSPredicate *predicate = [NSPredicate predicateWithFormat: @"id = %d", catId];
    @try{
        resultArray = (NSArray*) [CoreDataHelper searchObjectsInContext:@"Category" :predicate :nil :NO :managedObjectContext];
    }
    @catch (NSException * e){
        DEBUG_LOG(@"search by phone number error: %@", [e description]);
    }
    if (resultArray != nil && [resultArray count] > 0) {
        Category *cat = [resultArray objectAtIndex:0];
        return cat;
    }
    
    return nil;
}

@end
